var trap = function (height) {
  let len = height.length;
  if (len <= 2) {
    return 0
  }

  if (height.every((item) => item === 1)) {
    return 0;
  }

  let sum = 0;
  for (let i = 1; i < len - 1; i++) {
    let left = i - 1;
    let leftMax = height[i];
    let right = i + 1;
    let rightMax = height[i];

    while (left >= 0) {
      if (height[left] > leftMax) {
        leftMax = height[left]
      }
      left--;
    }

    while (right <= len - 1) {
      if (height[right] > rightMax) {
        rightMax = height[right]
      }
      right++
    }

    sum += Math.min(leftMax, rightMax) - height[i]
  }

  return sum;
};

var trap2 = function (height) {
  let len = height.length;
  if (len <= 2) return 0;

  let leftMax = new Array(len);
  leftMax[0] = height[0]
  let rightMax = new Array(len);
  rightMax[len - 1] = height[len - 1]

  for (let i = 1; i < len; i++) {
    leftMax[i] = Math.max(leftMax[i - 1], height[i])
  }

  for (let i = len - 2; i >= 0; i--) {
    rightMax[i] = Math.max(rightMax[i + 1], height[i])
  }

  let sum = 0;
  for (let i = 0; i < len; i++) {
    sum += Math.min(leftMax[i], rightMax[i]) - height[i]
  }

  return sum

}

let test1 = [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1];
let test2 = [4, 2, 0, 3, 2, 5]
let arr = [1, 1, 1, 1, 1, 1, 1]

console.log(trap2(arr));
